<style>
    .form-group{overflow: hidden}
</style>

<!-- Content Header (Page header) -->
<section class="content-header">
    <h1>
        管理
        <small>列表</small>
    </h1>
</section>

<!-- Main content -->
<section class="content" id="sale-app">

    <div class="row">
        <div class="col-md-12">
            <a v-show="show.list" class="btn btn-default" @click="getList">刷新</a>
            <a v-show="show.list" class="btn btn-info" @click="add">添加</a>
            <a v-show="show.edit" class="btn btn-warning" @click="showToggle('list')">返回</a>
        </div>
    </div>

    <div class="row" v-show="show.list">
        <div class="col-md-12">
            <table class="table table-responsive table-striped table-bordered">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>标题</th>
                    <th>方式</th>
                    <th>时间段</th>
                    <th>折扣/优惠</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="item in list">
                    <td>{{item.sales_id}}</td>
                    <td>{{item.sales_title}}</td>
                    <td>{{Types[item.sales_type]}}</td>
                    <td>{{item | TimeRange}}</td>
                    <td>
                        <span v-if="1==item.sales_type">{{item.sales_discount}}%</span>
                        <span v-if="2==item.sales_type">&yen;{{item.sales_amount}}%</span>
                        <span v-if="3==item.sales_type">赠品</span>
                    </td>
                    <td>
                        <a class="btn btn-primary btn-xs" @click="edit(item)">编辑</a>

                        <a v-if="!item.disabled" class="btn btn-danger btn-xs" @click="disableToggle(item)">禁用</a>
                        <a v-if="item.disabled" class="btn btn-success btn-xs" @click="disableToggle(item)">启用</a>
                    </td>
                </tr>
                </tbody>
                <tfoot>
                <tr>
                    <td colspan="100">
                        <page :rows="page.rows" :last="page.last" v-model="page.page"></page>
                    </td>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <div class="row" v-show="show.edit">
        <div class="col-md-10 col-md-offset-1" style="background: white">
            <div class="col-md-8 col-md-offset-2">
                <h3>编辑</h3>
                <div class="form">
                    <div class="form-group">
                        <label>标题：</label>
                        <input class="form-control" v-model="edit_item.sales_title">
                    </div>

                    <div class="form-group">
                        <label>描述：</label>
                        <textarea class="form-control" v-model="edit_item.sales_description"></textarea>
                    </div>

                    <div class="form-group">
                        <label>活动时间段：</label>
                        <input type="datetime-local" v-model="edit_item.start_time" placeholder="格式：2017-10-10 09:15"> -
                        <input type="datetime-local" v-model="edit_item.end_time" placeholder="格式：2017-10-10 09:15">
                    </div>

                    <div class="form-group">
                        <label>方式：</label>
                        <select class="form-control" v-model="edit_item.sales_type">
                            <option v-for="(t, n) in Types" :value="n">{{t}}</option>
                        </select>
                    </div>

                    <div class="form-group" v-show="1 == edit_item.sales_type">
                        <label>折扣率(%)：</label>
                        <input type="number" class="form-control" min="0.01" max="100" step="0.01" v-model="edit_item.sales_discount">
                    </div>

                    <div class="form-group" v-show="2 == edit_item.sales_type">
                        <label>优惠(￥)：</label>
                        <input type="number" class="form-control" min="0.01" step="0.01" v-model="edit_item.sales_amount">
                    </div>

                    <div class="form-group">
                        <label>赠送(可多选，不选表示无赠送)：</label>
                        <div class="col-md-12">
                            <a class="btn btn-warning btn-xs" @click="clearGifts">清空</a>
                            <a class="btn btn-info btn-xs" @click="resetGifts">重置</a>
                        </div>
                        <div class="col-md-12">
                            <div class="col-md-6">
                                <label>课程：<a class="btn btn-xs" @click="getCurriculum"><i class="fa fa-refresh"></i></a></label>
                                <select class="form-control" v-model="edit_item_gifts.curricula" multiple>
                                    <option v-for="c in curriculumList" :value="c.id">[{{c.id}}]{{c.name}} / &yen; {{c.price}}</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label>专栏：<a class="btn btn-xs" @click="getColumn"><i class="fa fa-refresh"></i></a></label>
                                <select class="form-control" v-model="edit_item_gifts.columns" multiple>
                                    <option v-for="c in columnList" :value="c.id">[{{c.id}}]{{c.title}} / &yen; {{c.price}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <br>

                    <div class="form-group">
                        <label>禁用：</label><input type="checkbox" class="checkbox" v-model="edit_item.disabled">
                    </div>
                    <br>
                    <div class="form-group">
                        <a class="btn btn-primary" @click="save">保存</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

</section>
<!-- /.content -->
<script>
    const FormatString = 'yyyy-mm-ddThh:ii';
    function formatTime(timestamp, fmt = null) {
        return new Date(timestamp * 1000).format(fmt || FormatString)
    }
    function getTime(timeStr) {
        var d = new Date(timeStr.replace('T', ' '));
        return d.getTime() / 1000;
    }

    function Sales(type) {
        this.sales_title = '';
        this.sales_type = type;
        var now = new Date();
        this.start_time = now.format(FormatString);
        now.setDate(now.getDate() + 1);
        this.end_time = now.format(FormatString);
        this.sales_discount = 100;
        this.sales_amount = 0.00;
        this.disabled = false;
    }
    function Gifts() {
        this.curricula = [];
        this.columns = [];
    }

    var Types = {
        1: '打折',
        2: '减免',
        3: '仅赠送',
    };
    var Items = {
        1: {name: '课程', field: ''},
        3: {name: '专栏', field: ''},
    };

    var sale_app = new Vue({
        el: '#sale-app',
        data: {
            list: [],
            edit_item: new Sales(1),
            curriculumList: [],
            columnList: [],
            edit_item_gifts: new Gifts(),
            page: {
                rows: 10,
                page: 1,
                last: 0,
                type: 0
            },
            show: {
                list: true,
                edit: false
            },
            sort_edit: false,
            AJAXIsRequesting: false,
            Types: Types,
            Items: Items
        },
        created: function () {
            this.getList();
            this.getCurriculum();
            this.getColumn();
        },
        methods: {
            getList: function () {
                if (this.AJAXIsRequesting) return;
                this.AJAXIsRequesting = true;

                ajax({
                    uri: '/sale/list',
                    data: this.page,
                    success: function (resp) {
                        this.list = resp.data;
                        this.AJAXIsRequesting = false;
                    }.bind(this)
                })
            },
            getCurriculum(){
                ajax({
                    uri: '/bills/curriculum_names',
                    success: function (resp) {
                        this.curriculumList = resp.data;
                    }.bind(this)
                })
            },
            getColumn(){
                ajax({
                    uri: '/common/column_names',
                    success: function (resp) {
                        this.columnList = resp.data;
                    }.bind(this)
                })
            },
            showToggle: function (prop) {
                for (var p in this.show) {
                    this.show[p] = (p === prop)
                }
            },
            clearGifts: function () {
                this.edit_item_gifts = new Gifts();
            },
            resetGifts: function () {
                this.edit_item_gifts = Object.assign(new Gifts(), this.edit_item.gifts);
            },
            add: function () {
                this.edit_item = new Sales(1);
                this.edit_item_gifts = new Gifts();
                this.showToggle('edit');
            },
            edit: function (item) {
                item.start_time = formatTime(item.sales_start_time);
                item.end_time = formatTime(item.sales_end_time);
                this.edit_item = item;
                this.edit_item_gifts = Object.assign(new Gifts(), item.gifts);
                this.showToggle('edit');
            },
            save: function () {

                var item = Object.assign({}, this.edit_item);
                if (!item.sales_title || !Types[item.sales_type]) {
                    alert('请完善资料');
                    return
                }
                item.sales_start_time = getTime(item.start_time);
                item.sales_end_time = getTime(item.end_time);
                item.disabled = item.disabled ? 1 : 0;

                var gifts = {};
                if (this.edit_item_gifts.curricula.length > 0) gifts.curricula = this.edit_item_gifts.curricula;
                if (this.edit_item_gifts.columns.length > 0) gifts.columns = this.edit_item_gifts.columns;
                item.gifts = gifts;

                ajax({
                    uri: '/sale/save',
                    data: item,
                    success: function (resp) {
                        this.edit_item_gifts = new Gifts();
                        this.showToggle('list');
                        this.getList();
                    }.bind(this)
                })
            },
            disableToggle: function (item) {
                var disabled = item.disabled ? 0 : 1;
                ajax({
                    uri: '/sale/disable',
                    data: {id: item.sales_id, disabled: disabled},
                    success: function (resp) {
                        if (resp.data > 0) {
                            item.disabled = disabled;
                        }
                    }
                })
            }
        },
        filters: {
            /**
             * @return {string}
             */
            TimeRange: function (item) {
                var fmt = 'mm月dd日hh:ii';
                return formatTime(item.sales_start_time,fmt) + "至" + formatTime(item.sales_end_time,fmt);
            }
        }
    })
</script>